﻿using AjaxControlToolkit;
using ASP;
using ClassLibrary.BusinessLayer.Facade;
using IPMS.AccessAuth;
using IPMS.BLL;
using Resources;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Globalization;
using System.Text;
using System.Threading;
using System.Web.Profile;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using SysOperationLayer.DBHandle;
using SysComm;


public partial class ProductAdd : Page, IRequiresSessionState
{
    LogDB m_logdb = new LogDB();
    protected void btnAdd_Click(object sender, EventArgs e)
    {
        Auth canAdd = new Auth(this.Session["UserId"].ToString(), string.Empty, "Product");
        if (!canAdd.CanAdd())
        {
           
        }
        else
        {
            this.setButtons("Add");
            this.setText(false);
            this.clearText();
            this.txtModel.ReadOnly = false;
            this.txtRevision.ReadOnly = false;
            this.txtModel.Enabled = true;
            this.txtRevision.Enabled = true;
            this.txtModel.Focus();
        }
    }

    protected void btnAddProjectToProduct_Click(object sender, EventArgs e)
    {
        this.GenerateOpenFilter();
    }

    protected void btnCancel_Click(object sender, EventArgs e)
    {
        this.clearText();
        this.setText(false);
        this.setButtons(string.Empty);
    }

    protected void btnDelete_Click(object sender, EventArgs e)
    {
        Auth canDelete = new Auth(this.Session["UserId"].ToString(), string.Empty, "Product");
        if (!canDelete.CanDelete())
        {          
        }
        else
        {
            try
            {
                if (Request["Model"] != null)
                {
                    this.ODSProducts.DeleteMethod = "Delete";
                    this.ODSProducts.DeleteParameters["Original_Model"].DefaultValue = Request["Model"];//this.GridViewProducts.DataKeys[this.GridViewProducts.SelectedIndex].Values["Model"].ToString();
                    this.ODSProducts.Delete();
                    this.clearText();
                   
                    this.setText(true);
                    this.setButtons(string.Empty);
                }
            }
            catch (Exception)
            {
              
            }
        }
    }

    protected void btnDeleteProject_Click(object sender, EventArgs e)
    {
        foreach (GridViewRow gvRow in this.gvProjects.Rows)
        {
            CheckBox cb = (CheckBox)gvRow.FindControl("cbDelete");
            if ((cb != null) && cb.Checked)
            {
                try
                {
                    ProductProject prdproject = new ProductProject(Request["Model"], this.gvProjects.DataKeys[gvRow.RowIndex].Values["ProjectCode"].ToString(), null, null, null);
                    prdproject.DeleteProductProject();                   
                }
                catch (ArgumentOutOfRangeException)
                {
                }
            }
        }
        this.gvProjects.DataBind();
        this.btnDelete.Enabled = this.gvProjects.Rows.Count != 0;
    }

    protected void btnModify_Click(object sender, EventArgs e)
    {
        Auth canUpdate = new Auth(this.Session["UserId"].ToString(), string.Empty, "Product");
        if (!canUpdate.CanUpdate())
        {
          
        }
        else
        {
            this.setButtons("Update");
            this.setText(false);
            this.txtModel.ReadOnly = true;
            this.txtRevision.ReadOnly = true;
            this.txtModel.Enabled = false;
            this.txtRevision.Enabled = false;
            this.txtModelName.Focus();
            this.GenerateOpenFilter();
        }
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        try
        {
            string trueUpdateStr = string.Empty;
            string falseUpdateStr = string.Empty;
            string trueInsertStr = string.Empty;
            string falseInsertStr = string.Empty;
            if (Session["Culture"] != null)
            {

                if (Session["Culture"].ToString() == "zh-TW")
                {
                    trueUpdateStr = "更新成功!";
                    falseUpdateStr = "更新失败!";
                    trueInsertStr = "添加成功!";
                    falseInsertStr = "添加失敗!";
                }
                else if (Session["Culture"].ToString() == "zh-CN")
                {
                    trueUpdateStr = "更新成功!";
                    falseUpdateStr = "更新失败!";
                    trueInsertStr = "添加成功!";
                    falseInsertStr = "添加失败!";
                }
                else
                {
                    trueUpdateStr = "Update succeed!";
                    falseUpdateStr = "Update failed!";
                    trueInsertStr = "Add succeed!";
                    falseUpdateStr = "Add failed!";
                }
            }

            if (this.cbForUpdate.Checked)
            {
                this.ODSProducts.UpdateMethod = "Update";
                this.ODSProducts.UpdateParameters["Model"].DefaultValue = this.txtModel.Text.ToString();
                this.ODSProducts.UpdateParameters["Revision"].DefaultValue = this.txtRevision.Text.ToString();
                this.ODSProducts.UpdateParameters["ModelName"].DefaultValue = this.txtModelName.Text.ToString();
                this.ODSProducts.UpdateParameters["Specification"].DefaultValue = this.txtSpecification.Text.ToString();
                this.ODSProducts.UpdateParameters["Remark1"].DefaultValue = this.txtRemarks1.Text.ToString();
                this.ODSProducts.UpdateParameters["Remark2"].DefaultValue = this.txtRemarks2.Text.ToString();
                this.ODSProducts.UpdateParameters["Remark3"].DefaultValue = this.txtRemarks3.Text.ToString();
                this.ODSProducts.UpdateParameters["Remark4"].DefaultValue = this.txtRemarks4.Text.ToString();
                this.ODSProducts.UpdateParameters["Remark5"].DefaultValue = this.txtRemarks5.Text.ToString();
                this.ODSProducts.UpdateParameters["DateFld1"].DefaultValue = IPDataFormat.ConvertDateFormat(this.txtDate1.Text.ToString(), 1);
                this.ODSProducts.UpdateParameters["DateFld2"].DefaultValue = IPDataFormat.ConvertDateFormat(this.txtDate2.Text.ToString(), 1);
                this.ODSProducts.UpdateParameters["DateFld3"].DefaultValue = IPDataFormat.ConvertDateFormat(this.txtDate3.Text.ToString(), 1);
                this.ODSProducts.UpdateParameters["DateFld4"].DefaultValue = IPDataFormat.ConvertDateFormat(this.txtDate4.Text.ToString(), 1);
                this.ODSProducts.UpdateParameters["DateFld5"].DefaultValue = IPDataFormat.ConvertDateFormat(this.txtDate5.Text.ToString(), 1);
                this.ODSProducts.UpdateParameters["DeciFld1"].DefaultValue = this.txtDeci1.Text.ToString();
                this.ODSProducts.UpdateParameters["DeciFld2"].DefaultValue = this.txtDeci2.Text.ToString();
                this.ODSProducts.UpdateParameters["UpdateBy"].DefaultValue = this.Page.User.Identity.Name.ToString();
                this.ODSProducts.UpdateParameters["CreateDate"].DefaultValue = IPDataFormat.ConvertDateFormat(this.txtCreateDate.Text.ToString(), 1);
                this.ODSProducts.UpdateParameters["Original_Model"].DefaultValue = this.txtModel.Text.ToString();

                if (this.ODSProducts.Update() < 0)
                {                      
                    IPMS.Common.Jscript.AlertAndRedirect(trueUpdateStr, "Product.aspx", this.Page);
                    m_logdb.writeSucLog(SysUtil.m_functiong_product, "update product information succeed!");
                }
                else
                {
                    IPMS.Common.Jscript.Alert(falseUpdateStr,this.Page);
                    m_logdb.writeFaileLog(SysUtil.m_functiong_product, "update product information faile!");
                }                
                
                this.btnCancel_Click(base.Server, e);
            }
            else
            {
                this.ODSProducts.InsertMethod = "Insert";
                this.ODSProducts.InsertParameters["Model"].DefaultValue = this.txtModel.Text.ToString();
                this.ODSProducts.InsertParameters["Revision"].DefaultValue = this.txtRevision.Text.ToString();
                this.ODSProducts.InsertParameters["ModelName"].DefaultValue = this.txtModelName.Text.ToString();
                this.ODSProducts.InsertParameters["Specification"].DefaultValue = this.txtSpecification.Text.ToString();
                this.ODSProducts.InsertParameters["Remark1"].DefaultValue = this.txtRemarks1.Text.ToString();
                this.ODSProducts.InsertParameters["Remark2"].DefaultValue = this.txtRemarks2.Text.ToString();
                this.ODSProducts.InsertParameters["Remark3"].DefaultValue = this.txtRemarks3.Text.ToString();
                this.ODSProducts.InsertParameters["Remark4"].DefaultValue = this.txtRemarks4.Text.ToString();
                this.ODSProducts.InsertParameters["Remark5"].DefaultValue = this.txtRemarks5.Text.ToString();
                this.ODSProducts.InsertParameters["DateFld1"].DefaultValue = IPDataFormat.ConvertDateFormat(this.txtDate1.Text.ToString(), 1);
                this.ODSProducts.InsertParameters["DateFld2"].DefaultValue = IPDataFormat.ConvertDateFormat(this.txtDate2.Text.ToString(), 1);
                this.ODSProducts.InsertParameters["DateFld3"].DefaultValue = IPDataFormat.ConvertDateFormat(this.txtDate3.Text.ToString(), 1);
                this.ODSProducts.InsertParameters["DateFld4"].DefaultValue = IPDataFormat.ConvertDateFormat(this.txtDate4.Text.ToString(), 1);
                this.ODSProducts.InsertParameters["DateFld5"].DefaultValue = IPDataFormat.ConvertDateFormat(this.txtDate5.Text.ToString(), 1);
                this.ODSProducts.InsertParameters["DeciFld1"].DefaultValue = this.txtDeci1.Text.ToString();
                this.ODSProducts.InsertParameters["DeciFld2"].DefaultValue = this.txtDeci2.Text.ToString();
                this.ODSProducts.InsertParameters["CreateBy"].DefaultValue = this.Page.User.Identity.Name.ToString();
                this.ODSProducts.InsertParameters["UpdateBy"].DefaultValue = this.Page.User.Identity.Name.ToString();
                this.ODSProducts.InsertParameters["OwnerGroupID"].DefaultValue = this.Session["OwnerGroupID"].ToString();
                this.ODSProducts.InsertParameters["CreateDate"].DefaultValue = IPDataFormat.ConvertDateFormat(this.txtCreateDate.Text.ToString(), 1);

                if (this.ODSProducts.Insert() < 0)
                {

                    IPMS.Common.Jscript.AlertAndRedirect(trueInsertStr, "Product.aspx", this.Page);
                    m_logdb.writeSucLog(SysUtil.m_functiong_product, "add product information succeed!");
                }
                else
                {
                    IPMS.Common.Jscript.Alert(falseInsertStr, this.Page);
                    m_logdb.writeFaileLog(SysUtil.m_functiong_product, "add product information faile!");
                }       
            }        
            this.cbForUpdate.Checked = false;
            this.setButtons(string.Empty);
            this.setText(true);
            this.clearText();
           
            this.SwitchTab(1);
            this.GenerateOpenFilter();
        }
        catch (Exception ex)
        {
            List<string> lstValues = new List<string>();
           
        }
    }   

    private void clearText()
    {
        this.txtModel.Text = string.Empty;
        this.txtRevision.Text = string.Empty;
        this.txtModelName.Text = string.Empty;
        this.txtSpecification.Text = string.Empty;
        this.txtCreateDate.Text = string.Empty;
        this.txtRemarks1.Text = string.Empty;
        this.txtRemarks2.Text = string.Empty;
        this.txtRemarks3.Text = string.Empty;
        this.txtRemarks4.Text = string.Empty;
        this.txtRemarks5.Text = string.Empty;
        this.txtDate1.Text = string.Empty;
        this.txtDate2.Text = string.Empty;
        this.txtDate3.Text = string.Empty;
        this.txtDate4.Text = string.Empty;
        this.txtDate5.Text = string.Empty;
        this.txtDeci1.Text = string.Empty;
        this.txtDeci2.Text = string.Empty;
        this.chkForOperation.Checked = false;
      
    }

    protected void GenerateOpenFilter()
    {

        StringBuilder sb = new StringBuilder();
        sb.AppendLine("<script> function OpenFilter() {");
        sb.AppendLine("window.showModalDialog('FilterProject.aspx?Model=" + Request["Model"] + "'");
        sb.AppendLine(",'newwindow', 'dialogHeight:600px; dialogWidth: 850px; dialogTop: 197px; dialogLeft: 894px; edge: Raised; center: Yes; resizable: No; status: Yes');");
        sb.AppendLine("}</script>");
        this.Page.ClientScript.RegisterClientScriptBlock(this.Page.GetType(), "OpenFilter", sb.ToString());

    }

   
    protected void ibGeneral_Click(object sender, ImageClickEventArgs e)
    {
        this.SwitchTab(1);
        this.GenerateOpenFilter();
    }

    protected void ibMisc_Click(object sender, ImageClickEventArgs e)
    {
        this.SwitchTab(2);
        this.GenerateOpenFilter();
    }

    protected void ibProject_Click(object sender, ImageClickEventArgs e)
    {
        this.SwitchTab(3);
        this.GenerateOpenFilter();
    }

    protected override void InitializeCulture()
    {
        string sCulture = ConfigurationManager.AppSettings["DefaultCulture"].ToString();
        try
        {
            sCulture = this.Session["Culture"].ToString();
        }
        catch (NullReferenceException)
        {
        }
        Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(sCulture);
        Thread.CurrentThread.CurrentUICulture = new CultureInfo(sCulture);
        base.InitializeCulture();
    }

    protected void Page_Load(object sender, EventArgs e)
    {

       Session["Model"] = Request["Model"];
        if (!IsPostBack)
        {
            ((Label)this.Master.FindControl("lblMstTitle")).Text = "| " + ISitemap.ProductManage.ToString() + " | " + ISitemap.NewProduct.ToString();

            //this.setButtons("Add");
            this.setText(false);
            this.clearText();
            this.txtModel.ReadOnly = false;
            this.txtRevision.ReadOnly = false;
            this.txtModel.Enabled = true;
            this.txtRevision.Enabled = true;
            this.txtModel.Focus();

            if (Request["Model"] != null)
            {
                PopulateProduct(Request["Model"]);
            }
        }

        Auth canView = new Auth(this.Session["UserId"].ToString(), string.Empty, "Product");
        if (!canView.CanView())
        {
            base.Response.Redirect("ErrorPage/NotAllowed.aspx");
        }
        else
        {
           // this.lblError.Visible = false;
            try
            {
                if (!this.Page.IsPostBack)
                {
                    this.setButtons(string.Empty);
                    this.setText(false);
                    this.SwitchTab(1);
                    this.btnDelete.Attributes.Add("onClick", "return confirm('" + Messages.DeleteConfirmation.ToString() + "')");
                    this.btnDeleteProject.Attributes.Add("onClick", "return confirm('" + Messages.DeleteConfirmation.ToString() + "')");
                }               
            }
            catch (NullReferenceException)
            {
            }
        }
        this.gvProjects.DataBind();
    }

    protected void PopulateProduct(string Model)
    {
        this.chkForOperation.Checked = true;
        this.cbForUpdate.Checked = true;
        ProductsClass runMethod = new ProductsClass();
        runMethod.GetProductInfo(Model);
        this.txtModel.Text = Model;
        this.txtRevision.Text = runMethod.Revision;
        this.txtModelName.Text = runMethod.ModelName;
        this.txtSpecification.Text = runMethod.Specification;
        this.txtCreateDate.Text = IPDataFormat.FormatDateTime(runMethod.CreateDate);
        this.txtRemarks1.Text = runMethod.Remark1;
        this.txtRemarks2.Text = runMethod.Remark2;
        this.txtRemarks3.Text = runMethod.Remark3;
        this.txtRemarks4.Text = runMethod.Remark4;
        this.txtRemarks5.Text = runMethod.Remark5;
        this.txtDate1.Text = IPDataFormat.FormatDateTime(runMethod.DateFld1);
        this.txtDate2.Text = IPDataFormat.FormatDateTime(runMethod.DateFld2);
        this.txtDate3.Text = IPDataFormat.FormatDateTime(runMethod.DateFld3);
        this.txtDate4.Text = IPDataFormat.FormatDateTime(runMethod.DateFld4);
        this.txtDate5.Text = IPDataFormat.FormatDateTime(runMethod.DateFld5);
        this.txtDeci1.Text = string.Format("{0:#,##0.00}", Convert.ToDecimal(runMethod.DeciFld1));
        this.txtDeci2.Text = string.Format("{0:#,##0.00}", Convert.ToDecimal(runMethod.DeciFld2));
        this.GenerateOpenFilter();
        this.setButtons(string.Empty);
       this.gvProjects.DataBind();
    }

     

    private void setButtons(string action)
    {
        //string strname0 = action;
        //if (strname0 != null)
        //{
        //    if (!(strname0 == "Add"))
        //    {
        //        if (strname0 == "Update")
        //        {
        //            this.btnAdd.Enabled = false;
        //            this.btnModify.Enabled = false;
        //            this.btnDelete.Enabled = false;
        //            this.btnSave.Enabled = true;
        //            goto Label_013D;
        //        }
        //        if (strname0 == "Save")
        //        {
        //            this.btnAdd.Enabled = true;
        //            this.btnModify.Enabled = true;
        //            this.btnDelete.Enabled = true;
        //            this.btnSave.Enabled = false;
        //            goto Label_013D;
        //        }
        //    }
        //    else
        //    {
        //        this.btnAdd.Enabled = false;
        //        this.btnModify.Enabled = false;
        //        this.btnDelete.Enabled = false;
        //        this.btnSave.Enabled = true;
        //        goto Label_013D;
        //    }
        //}
        this.btnAdd.Enabled = true;
        this.btnModify.Enabled = this.txtModel.Text.Length != 0;
        this.btnSave.Enabled = true;
        this.btnDelete.Enabled = this.txtModel.Text.Length != 0;
   // Label_013D:
        //if ((this.txtModel.Text.Length != 0) & this.txtModel.ReadOnly)
       // {
            this.btnAddProjectToProduct.Enabled = true;
        //}
        //else
        //{
          //  this.btnAddProjectToProduct.Enabled = false;
        //}
    }

    private void setText(bool bBool)
    {
        this.txtModel.ReadOnly = bBool;
        this.txtRevision.ReadOnly = bBool;
        this.txtModelName.ReadOnly = bBool;
        this.txtSpecification.ReadOnly = bBool;
        this.txtCreateDate.Enabled = !bBool;
        this.txtRemarks1.ReadOnly = bBool;
        this.txtRemarks2.ReadOnly = bBool;
        this.txtRemarks3.ReadOnly = bBool;
        this.txtRemarks4.ReadOnly = bBool;
        this.txtRemarks5.ReadOnly = bBool;
        this.txtDate1.Enabled = !bBool;
        this.txtDate2.Enabled = !bBool;
        this.txtDate3.Enabled = !bBool;
        this.txtDate4.Enabled = !bBool;
        this.txtDate5.Enabled = !bBool;
        this.txtDeci1.ReadOnly = bBool;
        this.txtDeci2.ReadOnly = bBool;
    }

   
    protected void SwitchTab(int Tab)
    {
        string culture = this.Session["Culture"].ToString().ToLower();
        switch (Tab)
        {
            case 1:
                this.PanelGeneral.Visible = true;
                this.PanelMisc.Visible = false;
                this.PanelProject.Visible = false;
                this.PanelButton.Visible = true;
                this.ibGeneral.ImageUrl = "~/Images/a_General_blue-" + culture + ".gif";
                this.ibMisc.ImageUrl = "~/Images/a_Others_gray-" + culture + ".gif";
                this.ibProject.ImageUrl = "~/Images/a_ProjectList_gray-" + culture + ".gif";
                break;

            case 2:
                this.PanelGeneral.Visible = false;
                this.PanelMisc.Visible = true;
                this.PanelProject.Visible = false;
                this.PanelButton.Visible = true;
                this.ibGeneral.ImageUrl = "~/Images/a_General_gray-" + culture + ".gif";
                this.ibMisc.ImageUrl = "~/Images/a_Others_blue-" + culture + ".gif";
                this.ibProject.ImageUrl = "~/Images/a_ProjectList_gray-" + culture + ".gif";
                break;

            case 3:
                this.PanelGeneral.Visible = false;
                this.PanelMisc.Visible = false;
                this.PanelProject.Visible = true;
                this.PanelButton.Visible = false;
                this.ibGeneral.ImageUrl = "~/Images/a_General_gray-" + culture + ".gif";
                this.ibMisc.ImageUrl = "~/Images/a_Others_gray-" + culture + ".gif";
                this.ibProject.ImageUrl = "~/Images/a_ProjectList_blue-" + culture + ".gif";
                this.gvProjects.DataBind();
                break;
        }
    }
    protected void btnBack_Click(object sender, EventArgs e)
    {
        Response.Redirect("Product.aspx");
    }
}
